package com.asynctm.android.socialnetwork.dao;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.asynctm.android.R;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

/**
 * Genera la conexcion e inicializa el api de Facebook
 * 
 * @author rockdrigo && rodmal
 *
 */
public class FacebookDao {

	private static final String APP_ID = "430755370271482";
	private static final String[] PERMISSIONS = new String[] { "publish_stream" };

	private static final String TOKEN = "access_token";
	private static final String EXPIRES = "expires_in";
	private static final String KEY = "facebook-credentials";

	private Activity activity;

	private Facebook facebook;
	private String messageToPost;

	/**
	 * Alamacena la cuenta de FB en memoria
	 * 
	 * @param facebook
	 * @return
	 */
	public boolean saveCredentials(Facebook facebook) {
		Editor editor = activity.getApplicationContext()
				.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
		editor.putString(TOKEN, facebook.getAccessToken());
		editor.putLong(EXPIRES, facebook.getAccessExpires());
		return editor.commit();
	}

	/**
	 * Recupera la cuenta de FB en memoria
	 * 
	 * @param facebook
	 * @return
	 */
	public boolean restoreCredentials(Facebook facebook) {
		SharedPreferences sharedPreferences = activity.getApplicationContext()
				.getSharedPreferences(KEY, Context.MODE_PRIVATE);
		facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
		facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
		return facebook.isSessionValid();
	}

	/**
	 * 
	 * @param activity
	 * @param message
	 */
	public FacebookDao(Activity activity, String message) {

		this.activity = activity;

		facebook = new Facebook(APP_ID);
		restoreCredentials(facebook);

		messageToPost = activity.getApplicationContext().getString(
				R.string.asynctmFB_Message)
				+ "\n"
				+ activity.getApplicationContext().getString(
						R.string.asynctmFB_URL);

	}

	/**	Comparte el mensaje predeterminado en el muro */
	public void share() {
		if (!facebook.isSessionValid()) {
			loginAndPostToWall();
		} else {
			postToWall(messageToPost);
		}
	}

	/**	Logea en FB */
	private void loginAndPostToWall() {
		facebook.authorize(activity, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
				new LoginDialogListener());
	}

	/** 
	 * Publica un message en el muro
	 * 
	 * @param message
	 */
	private void postToWall(String message) {
		Bundle parameters = new Bundle();
		parameters.putString("message", message);
		parameters.putString("picture", "http://miguelangellv.files.wordpress.com/2011/01/androidclock.png");
		parameters.putString("description", "topic share");
		try {
			facebook.request("me");
			String response = facebook.request("me/feed", parameters, "POST");
			Log.d("Tests", "got response: " + response);
			if (response == null || response.equals("")
					|| response.equals("false")) {
				showToast(activity.getApplicationContext().getString(
						R.string.msg_service_unavailable));
			} else {
				showToast(activity.getApplicationContext().getString(
						R.string.msg_FBshare_complete));
			}
		} catch (Exception e) {
			showToast(activity.getApplicationContext().getString(
					R.string.msg_FBshare_error));
			e.printStackTrace();
		}
	}

	/**
	 * Recibe los errores y referencias de la conexcion a FB
	 * 
	 * @author rockdrigo
	 */
	private class LoginDialogListener implements DialogListener {
		public void onComplete(Bundle values) {
			saveCredentials(facebook);
			if (messageToPost != null) {
				postToWall(messageToPost);
			}
		}

		public void onFacebookError(FacebookError error) {
			showToast(activity.getApplicationContext().getString(
					R.string.msg_FBlogin_error));
		}

		public void onError(DialogError error) {
			showToast(activity.getApplicationContext().getString(
					R.string.msg_FBlogin_error));
		}

		public void onCancel() {
			// showToast("Authentication with Facebook cancelled!");
		}
	}

	private void showToast(String message) {
		Toast.makeText(activity.getApplicationContext(), message,
				Toast.LENGTH_SHORT).show();
	}
}